/**
 * 全局api请求模块
 * @param {Object} Vue Vue的实例
 * @param {Object} options 请求配置
 * @return 返回请求后结果 Promise
 */
import {globalConfig}  from './config'
import { resolve } from 'url';
import { rejects } from 'assert';
export default {
    install (Vue,options) {
        // 默认参数配置
        const DEFAULT_CONFIG = {
            load: true,                                         // 是否显示loading
            method: 'POST',                                     // 默认POST提交                 
            contentType: 'application/x-www-form-urlencoded'    // 默认contentType
        }
        Vue.prototype.$ajax = (options = {}) => {
            console.log(options)
            let params = Object.assign({}, DEFAULT_CONFIG, options)
            // 如果当前是json格式
            let type = params.contentType ? 'application/json' : params.contentType
            return new Promise((resolve,rejects) => {
                params.load &&  wx.showLoading({
                    title: '数据加载中'
                })
                wx.request({
                    method: params.method,
                    data: params.data,
                    url: `${globalConfig.netWorkUrl}${params.api}`,
                    header: {
                        'Content-Type': params.contentType
                    },
                    success(result) {
                        if(result.data.status === globalConfig.successCode){
                            resolve({
                                data: result.data.data,
                                status: globalConfig.successCode
                            })
                            return
                        }
                        rejects({
                            status: result.data.status,
                            message: result.data.message
                        })
                    },
                    fail(error) {
                        rejects({
                            status: globalConfig.errorCode ,
                            message: '服务器错误'
                        })  
                    }
                })
            }) 
        }
    }
}
